<!--
@name:tabFrequentlyMeasuredItems
@author:Zhenglei
@date:9:39
@description:tabFrequentlyMeasuredItems
@update:2022/7/149:39
-->
<template>
  <div class="pd-20">
    <h2 style="font-weight: bold;margin-bottom:36px">常测项目：</h2>
    <el-button type="primary" @click="handleOption('addTheme')" style="margin-bottom: 20px">增 加</el-button>

    <el-card v-for="(item,index0) in formModel.themes" :key="index0" style="margin-bottom: 20px">
      <div slot="header" style="display: flex;flex-direction: row;align-items: center;justify-content: space-between">
        <h3 style="font-weight: bold">常测主题{{ index0 + 1 }}:</h3>
        <el-button @click="handleOption('delTheme',index0)" type="danger">删除</el-button>
      </div>

      <el-form :model="item"
               label-position="right"
               label-width="120px">
        <el-form-item label="主题名称：" class="is-required">
          <el-input v-model="item.themeName"
                    clearable
                    class="w-300"
                    placeholder="请输入主题名称"></el-input>
          <el-input v-model="item.sortNum"
                    type="number"
                    class="w-200"
                    placeholder="请输入主题排序"></el-input>
        </el-form-item>

        <el-form-item label="检测项目：" class="is-required">
          <el-select v-model="item.detectionItemId"
                     filterable
                     class="w-300"
                     @change="handleChangeDetect"
                     placeholder="请选择检测项目">
            <el-option v-for="item in detectionDataSource"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="item.indexIds"
                     clearable
                     class="w-200"
                     multiple
                     placeholder="请选择检测指标">
            <el-option v-for="item in targetDataSource"
                       :key="item.referenceId"
                       :label="item.referenceName"
                       :value="item.referenceId">
            </el-option>
          </el-select>
          <el-input v-model="item.sort"
                    type="number"
                    style="width: 100px"
                    placeholder="排序"/>
          <el-button type="primary" @click="handleOption('addDetection',index0)">增 加</el-button>
        </el-form-item>

        <el-form-item>
          <element-table :columns="columns"
                         :data="item.detectIndexes"
                         :is-show-null="false"
                         :span-method="(param)=>objectSpanMethod(param,item.detectIndexes)"
                         v-loading="loading">
            <template v-slot:sortNum="{row,index}">
              <el-input-number v-model="row.sortNum" controls-position="right" :min="1"/>
            </template>
            <template v-slot:option="{row,index}">
              <el-button type="success"
                         v-if="row.onTop===0"
                         @click="handleOption('settingTop',index0,index)">设为置顶
              </el-button>
              <el-button type="info"
                         v-if="row.onTop===1"
                         @click="handleOption('cancleTop',index0,index)">取消置顶
              </el-button>
              <el-button type="danger"
                         @click="handleOption('delDetection',index0,index)">删除
              </el-button>
            </template>
          </element-table>
        </el-form-item>


      </el-form>

    </el-card>
    <p style="margin-top: 20px" v-if="formModel.themes.length!==0">
      <el-button type="primary"
                 size="medium"
                 v-prevent-re-click
                 @click="handleOption('save')">保 存
      </el-button>
    </p>

  </div>
</template>

<script>
import ElementTable from "../../../../base/ElementTable";

export default {
  name: "tabFrequentlyMeasuredItems",
  data() {
    return {
      formModel: {
        type: 3,
        themes: []
      },
      detectionDataSource: [],
      targetDataSource: [],
      loading: false,
      columns: [
        {
          label: '检测项目',
          prop: 'deviceName',
          align: 'center'
        }, {
          label: '检测指标',
          prop: 'indexName',
          align: 'center'
        }, {
          label: '排序',
          prop: 'sortNum',
          align: 'center',
          isSlot: true
        }, {
          label: '操作',
          prop: 'option',
          align: 'center',
          isSlot: true,
          width: 300
        }
      ]

    }
  },
  created() {
    this.getAllDeviceList()
    this.getDiscLifeDetail()
  },
  methods: {
    //获取详情
    getDiscLifeDetail() {
      this.post(this.api.healthMap.getDiscLifeDetail, {type: 3}).then((res) => {
        if (res.data.code === '200') {
          this.formModel.themes = res.data.object
          //TODO 合并操作项
          // this.formModel.themes.forEach(item=>{
          //   item.detectIndexes.forEach(o=>{
          //     this.$set(o,'option',o.deviceName)
          //   })
          // })
        }
      })
    },
    //查询检测项
    getAllDeviceList() {
      this.post(this.api.healthMap.getAllDeviceList, {
        pageSize: 500
      }).then((res) => {
        if (res.data.code === '200') {
          this.detectionDataSource = res.data.object
        }
      })
    },
    //检测项查询指标
    getDeviceReferenceByDeviceId(deviceId) {
      this.post(this.api.healthMap.getDeviceReferenceByDeviceId, {
        deviceId: deviceId
      }).then((res) => {
        if (res.data.code === '200') {
          this.targetDataSource = res.data.object.referenceDtoList
        }
      })
    },
    handleChangeDetect(val) {
      this.getDeviceReferenceByDeviceId(val)
    },
    handleOption(op, index0, index) {
      switch (op) {
        case 'addTheme':
          this.formModel.themes.push({
            themeName: '',
            sortNum: '',
            detectIndexes: [],
          })
          break;

        case 'delTheme':
          this.$confirm('删除后，相应指标在生命圆盘不显示，可能影响其他指标数据!', '提示', {
            type: 'warning'
          }).then(() => {
            this.formModel.themes.splice(index0, 1)
          })
          break;
        case 'addDetection':
          if (!this.formModel.themes[index0].detectionItemId) {
            this.$message.warning('请选择检测项名称')
          } else if (this.formModel.themes[index0].indexIds.length === 0) {
            this.$message.warning('请选择检测项指标')
          } else if (!this.formModel.themes[index0].sort) {
            this.$message.warning('请输入检测项排序')
          } else {
            let indexIds = this.formModel.themes[index0].indexIds;
            let allIndexIds = this.formModel.themes[index0].detectIndexes.map(x => x.indexId)
            let isClude = allIndexIds.filter(x => {
              return indexIds.indexOf(x) > -1
            })
            if (isClude.length>0) {
              //已经存在指标
              this.$message.warning('已存在该指标！')
              return
            }

            let deviceName = this.detectionDataSource.find(item => item.id === this.formModel.themes[index0].detectionItemId).name;
            this.formModel.themes[index0].indexIds.forEach((item, index) => {
              this.formModel.themes[index0].detectIndexes.push({
                deviceId: this.formModel.themes[index0].detectionItemId,
                indexId: item,
                sortNum: parseInt(this.formModel.themes[index0].sort) + index,
                deviceName: deviceName,
                indexName: this.targetDataSource.find(o => o.referenceId === item).referenceName,
                onTop: 0,//是否置顶
              })
            })

            this.formModel.themes[index0].detectionItemId = ''
            this.formModel.themes[index0].indexIds = []
            this.formModel.themes[index0].sort = ''
            deviceName = ''
          }

          break;
        case 'delDetection':
          this.$confirm('删除后，相应指标在生命圆盘不显示，可能影响其他指标数据!', '提示', {
            type: 'warning'
          }).then(() => {
            this.formModel.themes[index0].detectIndexes.splice(index, 1)
          })
          break
        case 'settingTop':
          this.formModel.themes[index0].detectIndexes[index].onTop = 1
          break
        case 'cancleTop':
          this.formModel.themes[index0].detectIndexes[index].onTop = 0
          break
        case 'save':
          let list = this.formModel.themes
          let isName = list.every(o => o.themeName)
          let isSort = list.every(o => o.sortNum)
          let isDetectionList = list.every(o => o.detectIndexes.length > 0)
          if (!isName) {
            this.$message.warning('请输入主题名称')
          } else if (!isSort) {
            this.$message.warning('请输入主题排序')
          } else if (!isDetectionList) {
            this.$message.warning('请添加检测项')
          } else {
            this.post(this.api.healthMap.discLifeOpr, this.formModel).then((res) => {
              if (res.data.code === '200') {
                this.$message.success('保存成功！')
              }
            })
          }
          break

      }

    },
    /**
     * 封装--合并单元格--合并列
     * 本方法参数参照
     * https://element.eleme.cn/#/zh-CN/component/table
     */
    objectSpanMethod({
                       row,
                       column,
                       rowIndex,
                       columnIndex,

                     }, data) {
      if (row[column.property]) { // 空值不合并
        if (columnIndex === 0 || columnIndex === 3) { // 合并那一列
          return this.whetherVertical(column.property, row[column.property], rowIndex, data)
        }
      }
    },
    /**
     * 调用--获取合并列个数
     * @param {String} key 当前单元格key
     * @param {String} value 当前单元格value
     * @param {Number} site 当前单元格下标
     * @param list 数据源
     */
    whetherVertical(key, value, site, list) {
      // const list = this.formModel.themes[1].detectIndexes // 获取当前页所有数据
      // 如果该数据下标不为0并且与上一格相同，该单元格被合并
      if (site > 0 && list[site - 1][key] === value) {
        return [0, 0]
      }
      // 获取当前单元格合并个数，如果下一格不同，则返回1
      const num = this.getVerticalSum(key, value, list, site, 1)
      return [num, 1]
    },
    /**
     * 递归--查询合并列数量
     * @param {String} key 当前参数key
     * @param {String} value 当前参数value
     * @param {Array} list 当前查询集合
     * @param {Number} site 当前所在下标
     * @param {Number} sum 合并个数（递归增加）
     */
    getVerticalSum(key, value, list, site, sum) {
      // 是否下一项存在
      if (list[site + 1]) {
        // 判断下一项是否符合条件
        if (list[site + 1][key] === value) {
          return this.getVerticalSum(key, value, list, site + 1, sum + 1)
        } else {
          return sum
        }
      } else {
        return sum
      }
    },
  },
  components: {
    'element-table': ElementTable,
  }
}
</script>

<style scoped>

</style>
